const express = require("express");
const multer = require("multer");

const app = express();

// 解码 form-data
// dest: "./public/uploads" 上传文件的存放目录
// req.file, 存放上传文件的信息
// single("myfile")) 指定上传文件数据的字段名
app.use(multer({ dest: "./public/uploads" }).single("myfile"));
// 解码 urlencoded，json
app.use(express.urlencoded());
app.use(express.json());

app.post("/up", (req, res) => {
  res.send({
    message: "hello",
    body: req.body,
    file: req.file,
  });
});

app.post("/comments", (req, res) => {
  res.send({
    header: req.headers,
    body: req.body,
  });
});

app.get("/xml", (req, res) => {
  res.type("xml");
  res.send(`
    <user>
      <name>jack</name>
      <age>20</age>
      <gender>boy</gender>
    </user>
  `);
});

app.get("/img", (req, res) =>
  res.sendFile("F:/code-212/20240126/public/imgs/1.png")
);
//http://localhost:8081/posts
app.get("/video", (req, res) => res.sendFile("f://video/8.json-server6.mp4"));

//http://localhost:8081/posts/2
/* app.get("/posts/:id", (req, res) => res.send(
  db.posts.find(el=>el.id===req.params.id)
)); */

//http://localhost:8081/posts 新增
// app.post("/posts", (req, res) => {
//   const body = req.body;
//   db.posts.push(body); // 和数据库交互
//   res.status(201)
//   res.send(body);
// });

//http://localhost:8081/posts/1 修改
// app.put("/posts/:id", (req, res) => {
//   const body = req.body;
//   const id = req.params.id;
//   // 和数据库交互
//   const index = db.posts.findInde((el) => el.id === id);
//   db.posts.splice(index, 1, body);
//   res.status(200);
//   res.send(body);
// });

//http://localhost:8081/posts/1 修改
// app.patch("/posts/:id", (req, res) => {
//   const body = req.body;
//   const id = req.params.id;
//   // 和数据库交互
//   const obj = db.posts.find((el) => el.id === id);
//   Object.entries(body).forEach((el) => {
//     obj[el[0]] = obj[el[1]];
//   });
//   res.status(200);
//   res.send(body);
// });

//http://localhost:8081/posts/1 删除
// app.delete("/posts/:id", (req, res) => {
//   const body = req.body;
//   const id = req.params.id;
//   // 和数据库交互
//   const index = db.posts.findIndex((el) => el.id === id);
//   db.posts.splice(index, 1);
//   res.status(200);
//   res.send({});
// });

module.exports = app;
